package grib2handler.grib.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import grib2handler.grib.pass.UVPass;
import grib2handler.util.FileUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool.Config;
import org.apache.log4j.Logger;

import grib2handler.grib.GribPoolDownTask;
import grib2handler.grib.netcdf.GribPass;
import grib2handler.grib.pass.HeightPass;
import grib2handler.grib.pass.RHPass;
import grib2handler.grib.pass.TemperPass;
import grib2handler.util.PropertiesUtil;
/**
 * ftp链接线程封装
 * @author charlie
 *
 */
public class FTPLinkPool extends Thread {
	private final static Logger logger = Logger.getLogger( FTPLinkPool.class );
	private static List<FTPPoolListener> lisList = new ArrayList<FTPPoolListener>();
	
	private static FTPPool pool;
	/**
	 * 远程路径
	 */
	private String remote = "";
	/**
	 * 本地保存路径
	 */
	private String local = "";
	/**
	 * 文件时间
	 */
	private String time = "";
	/**
	 * 文件名称
	 */
	private String fileName = "";
	/**
	 * 远程文件
	 */
	private FTPFile  remortFile = null;
	static {
		/**
		 *  初始化连接池
		 */
		GenericObjectPool.Config config = new Config();
		// 则每timeBetweenEvictionRunsMillis毫秒检查一次连接池中空闲的连接,
	    //把空闲时间超过minEvictableIdleTimeMillis毫秒的连接断开,直到连接池中的连接数到minIdle为止
		config.timeBetweenEvictionRunsMillis = 10000;//10秒检查一次
		//连接在池中保持空闲而不被空闲连接回收器线程(如果有)回收的最小时间值，单位毫秒
		config.minEvictableIdleTimeMillis = 120000;//最小保留2分钟
		// 在每次空闲连接回收器线程(如果有)运行时检查的连接数量
		config.numTestsPerEvictionRun = 5;//每次回收5个             
		//最大池容量
		config.maxActive=5;
		//最大空闲
		config.maxIdle=5;
		//最小空闲
		config.minIdle=0;
		//从池中取对象达到最大时,继续创建新对象.
		config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
		//池为空时取对象等待的最大毫秒数.
		config.maxWait=60*1000;
		//取出对象时验证(此处设置成验证ftp是否处于连接状态).
		config.testOnBorrow=true;
		//还回对象时验证(此处设置成验证ftp是否处于连接状态).
		config.testOnReturn=true;
		pool = new FTPPool(config,PropertiesUtil.getConfig().getString("ftp.ip"),21,PropertiesUtil.getConfig().getString("ftp.user"),PropertiesUtil.getConfig().getString("ftp.pass"),"true");
		
		/**
		 * 初始化监听器
		 */
		//注册ftp下载状态监听器，监听文件是否下载成功，进行后续操作
		FTPLinkPool.addLis(new FTPPoolListener() {
			
			@Override
			public void onSuccess(FTPLinkPool ftp) {
				logger.info("****" + ftp.getRemote() + "下载成功");
				logger.info("****开始尝试解压文件: " + ftp.getLocal());
				File tarFile=new File(ftp.getLocal());
				if(FileUtil.unTar(tarFile, "")){
					logger.info("****解压文件成功: " + ftp.getLocal());
					File[] unTarFiles = tarFile.getParentFile().listFiles(new FilenameFilter() {
						
						@Override
						public boolean accept(File dir, String name) {
							// TODO Auto-generated method stub
							if(name.toLowerCase().endsWith(".tar")){
								return false;
							}
							return true;
						}
					});
					//解析成可读文件
					for(File f : unTarFiles){
						String fileNoExt=f.getName().substring(0, f.getName().indexOf("."));
						new GribPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(fileNoExt);
						new TemperPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(fileNoExt);
						new RHPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(fileNoExt);
						new HeightPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(fileNoExt);
						new UVPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(fileNoExt);
					}
				}
				//解析成可读文件
//				new GribPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(ftp.getFileName());
//				//解析成地图可取文件
//				if(ftp.getFileName().contains("WAFS_blended")) {
//					new CatPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(ftp.getFileName());
//					new IcePass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(ftp.getFileName());
//					new CbPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(ftp.getFileName());
//					new IncldturbPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(ftp.getFileName());
//				} else if(ftp.getFileName().contains("wafs_grb45")) {
//					new TemperPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(ftp.getFileName());
//					new RHPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(ftp.getFileName());
//					new HeightPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(ftp.getFileName());
//					new UVPass(ftp.getTime(), PropertiesUtil.getConfig().getString("agency", "us_avn"), "gfs").dopass(ftp.getFileName());
//				}
			}
			
			@Override
			public void onNoexist(FTPLinkPool ftp) {
				//略过，下载前已经多次检查文件存在
				logger.warn("****" + ftp.getRemote() + "文件不存在");
			}
			
			@Override
			public void onFailed(FTPLinkPool ftp) {
				logger.warn("****" + ftp.getRemote() + "下载失败断点重试");
				//下载失败过一段时间重新下载，20次失败后放弃下载（可能断网引起，采用断线续传）
				for (int i = 0; i < 20; i++) {
					try {
						Thread.sleep(180000);
					} catch (Exception e) {
					}
					try {
						DownloadStatus status = ftp.download(true);
						if(status.equals(DownloadStatus.Download_From_Break_Success) ||
							status.equals(DownloadStatus.Local_Bigger_Remote) ||
							status.equals(DownloadStatus.Download_New_Success)) {
							break;
						}
					} catch (Exception e) {
						logger.error("下载重试失败" + ftp.getRemote() + e.getMessage());
					}
				}
				
			}
		});
	}
	public static void addLis(FTPPoolListener lis) {
		lisList.add(lis);
	}
	public FTPLinkPool(String remote, String local, String time, String fileName) {
		this.remote = remote;
		this.local = local;
		this.time = time;
		this.fileName = fileName;
	}
	
	@Override
	public void run() {
		//检查文件是否存在
		for (int i = 0; i < 50; i++) {
			GribPoolDownTask.setLastRunTime(System.currentTimeMillis());
			if(checkRemortFile()) {
				logger.info("远程文件存在，即将执行下载" + remote);
				break;
			}
			try {
				logger.info("远程文件目前不存在，休眠后再试" + remote);
				Thread.sleep(10 * 60 * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		DownloadStatus ds = download(false);
		logger.info(ds);
	}

	public DownloadStatus download(boolean isFillRetry) {
		return download(remote, local, isFillRetry);
	}
	/**
	 * 检查远程文件是否存在
	 * @return
	 */
	private boolean checkRemortFile() {
		
		// 检查远程文件是否存在
		boolean flag = false;
		FTPClient ftpClient = null;
		try {
			ftpClient = pool.getResource();
			if(pool.isPassiveMode()) {
				ftpClient.enterLocalPassiveMode();// Use passive mode to pass firewalls.
			}
			FTPFile[] files = ftpClient.listFiles(new String(
					remote.getBytes("GBK"), "iso-8859-1"));
			//只能查到一个文件
			if (files.length == 1) {
				// 获得远端文件大小
				long lRemoteSize = files[0].getSize();
				if(lRemoteSize > 0) {
					remortFile = files[0];
					flag =  true;
				}
			}
		} catch (Exception e) {
			logger.error("检验远程文件失败" + remote + e.getMessage());
		} finally {
			if(ftpClient != null) {
				pool.returnResource(ftpClient);
			}
		}
		return flag;
	}
	/**
	 * 获取目录时间列表
	 * @return
	 */
	public List<String> getFileTimes() {
		List<String> nameList = new ArrayList<String>();
		FTPClient ftpClient = null;
		try {
			ftpClient = pool.getResource();
			if(pool.isPassiveMode()) {
				ftpClient.enterLocalPassiveMode();// Use passive mode to pass firewalls.
			}
//			FTPFile[] files = ftpClient.listFiles(new String(
//					remote.getBytes("GBK"), "iso-8859-1"));
			FTPFile[] files = ftpClient.listFiles(remote);
			if (files.length > 0) {
				for (FTPFile ftpFile : files) {
					if(ftpFile.getName().startsWith("ldgrib2_")) {
						String temp = ftpFile.getName().replace("ldgrib2_", "");
						nameList.add(temp);
					}
				}
			}
		} catch (Exception e) {
			logger.error("获取最新的目录时间失败" + remote + e.getMessage());
		} finally {
			if(ftpClient != null) {
				pool.returnResource(ftpClient);
			}
		}
		Collections.sort(nameList);
		return nameList;
	}
	
	/**
	 * 文件整个下载，支持断点重下，显示不了进度
	 * @param remote
	 * @param local
	 * @param isFillRetry
	 * @return
	 */
	protected DownloadStatus download(String remote, String local, boolean isFillRetry) {
		GribPoolDownTask.setLastRunTime(System.currentTimeMillis());
		// 下载状态
		DownloadStatus result;
		// 本地文件列表
		File f = new File(local);
        //判断目标文件所在的目录是否存在
        if(!f.getParentFile().exists()) {
            //如果目标文件所在的目录不存在，则创建父目录
        	logger.info("目标文件所在目录不存在，准备创建它！");
            if(!f.getParentFile().mkdirs()) {
            	logger.error("创建目标文件所在目录失败！");
            }
        }

        FTPClient ftpClient = null;
        long lRemoteSize = Long.MAX_VALUE;
		try {
			logger.info(remote + "开始下载");
			ftpClient = pool.getResource();
			logger.info(remote + "ftp连接获取成功");

			if (remortFile == null) {
				logger.error(remote + "远程文件不存在");
				for (FTPPoolListener lis : lisList) {
					if(!isFillRetry) 
						lis.onNoexist(this);
				}
				return DownloadStatus.Remote_File_Noexist;
			}
			// 获得远端文件大小
			lRemoteSize = remortFile.getSize();
			// 构建输出对象
			OutputStream out = null;

			// 本地存在文件，进行断点下载 ；不存在则新下载
			if (f.exists()) {
				// 构建输出对象
				out = new FileOutputStream(f, true);
				// 本地文件大小
				long localSize = f.length();
				logger.info(local + "本地文件大小为:" + localSize);

				// 判定本地文件大小是否大于远程文件大小
				if (localSize >= lRemoteSize) {
					logger.info(local + "本地文件已经存在，下载中止");
					out.close();
					return DownloadStatus.Local_Bigger_Remote;
				}
				// 否则进行断点续传，并记录状态
				ftpClient.setRestartOffset(localSize);
				if(pool.isPassiveMode()) {
					ftpClient.enterLocalPassiveMode();// Use passive mode to pass firewalls.
				}
				ftpClient.retrieveFile(new String(remote
						.getBytes("GBK"), "iso-8859-1"), out);
				logger.info(remote + "断点下载结束");
				out.flush();
				out.close();
				if (f.length() >= lRemoteSize) {
					for (FTPPoolListener lis : lisList) {
						lis.onSuccess(this);
					}
					result = DownloadStatus.Download_From_Break_Success;
				} else {
					for (FTPPoolListener lis : lisList) {
						if(!isFillRetry) 
							lis.onFailed(this);
					}
					result = DownloadStatus.Download_From_Break_Failed;
				}
			} else {
				out = new FileOutputStream(f);
				if(pool.isPassiveMode()) {
					ftpClient.enterLocalPassiveMode();// Use passive mode to pass firewalls.
				}
				ftpClient.retrieveFile(new String(remote
						.getBytes("GBK"), "iso-8859-1"), out);
				logger.info(remote + "下载结束");
				out.flush();
				out.close();
				if (f.length() >= lRemoteSize) {
					for (FTPPoolListener lis : lisList) {
						lis.onSuccess(this);
					}
					result = DownloadStatus.Download_New_Success;
				} else {
					for (FTPPoolListener lis : lisList) {
						if(!isFillRetry) 
							lis.onFailed(this);
					}
					result = DownloadStatus.Download_New_Failed;
				}
			}
		} catch (Exception e) {
			
			//有可能已经下载完成，出现一些异常做下过滤
			if (f.length() >= lRemoteSize) {
				logger.warn("下载文件异常,但是数据已经下载完成" + remote + e.getMessage());
				for (FTPPoolListener lis : lisList) {
					lis.onSuccess(this);
				}
				result = DownloadStatus.Download_New_Success;
			} else {
				logger.error("下载文件失败" + remote + e.getMessage());
				for (FTPPoolListener lis : lisList) {
					if(!isFillRetry) 
						lis.onFailed(this);
				}
				result = DownloadStatus.Download_New_Failed;
			}
		} finally {
			if(ftpClient != null) {
				pool.returnResource(ftpClient);
			}
		}  
		return result;
	}
	/**
	 * 从FTP服务器上下载文件,支持断点续传功能
	 * 续传目前linux上还有点问题，而且windows上小文件传输性能并不高
	 * @param remote
	 *            远程文件路径
	 * @param local
	 *            本地文件路径
	 * @param mode
	 *            tb传输方式：PassiveMode方式，ActiveMode方式
	 * @param isFillRetry
	 *            是否是失败后重下载
	 * @return 是否成功
	 * @throws IOException
	 */
	@Deprecated
	protected DownloadStatus download1(String remote, String local, boolean isFillRetry) {
		// 下载状态
		DownloadStatus result;

		// 本地文件列表
		File f = new File(local);
        //判断目标文件所在的目录是否存在
        if(!f.getParentFile().exists()) {
            //如果目标文件所在的目录不存在，则创建父目录
        	logger.info("目标文件所在目录不存在，准备创建它！");
            if(!f.getParentFile().mkdirs()) {
            	logger.error("创建目标文件所在目录失败！");
            }
        }

        FTPClient ftpClient = null;
		try {
			logger.info(remote + "开始下载");
			ftpClient = pool.getResource();
			logger.info(remote + "ftp连接获取成功");

			if (remortFile == null) {
				logger.error(remote + "远程文件不存在");
				for (FTPPoolListener lis : lisList) {
					if(!isFillRetry) 
						lis.onNoexist(this);
				}
				return DownloadStatus.Remote_File_Noexist;
			}
			// 获得远端文件大小
			long lRemoteSize = remortFile.getSize();
			// 构建输出对象
			OutputStream out = null;

			// 本地存在文件，进行断点下载 ；不存在则新下载
			if (f.exists()) {
				// 构建输出对象
				out = new FileOutputStream(f, true);
				// 本地文件大小
				long localSize = f.length();
				logger.info(local + "本地文件大小为:" + localSize);

				// 判定本地文件大小是否大于远程文件大小
				if (localSize >= lRemoteSize) {
					logger.info(local + "本地文件已经存在，下载中止");
					out.close();
					return DownloadStatus.Local_Bigger_Remote;
				}

				// 否则进行断点续传，并记录状态
				ftpClient.setRestartOffset(localSize);
				if(pool.isPassiveMode()) {
					ftpClient.enterLocalPassiveMode();// Use passive mode to pass firewalls.
				}
				InputStream in = ftpClient.retrieveFileStream(new String(remote
						.getBytes("GBK"), "iso-8859-1"));

				byte[] bytes = new byte[4096];
				long step = lRemoteSize / 100;

				// 存放下载进度
				long process = localSize / step;
				int c;
				while ((c = in.read(bytes)) != -1) {
					logger.info(remote + "****" + c);
					out.write(bytes, 0, c);
					localSize += c;
					long nowProcess = localSize / step;
					if (nowProcess > process) {
						process = nowProcess;
						if (process % 10 == 0)
							logger.info(remote + "下载进度：" + process + "%");
						// 更新文件下载进度,值存放在process变量中
					}
				}
				logger.info(remote + "下载结束" + c);
				// 下载完成关闭输入输出流对象
				boolean isDo = false;
				long time = System.currentTimeMillis();
				try {
					in.close();
					logger.warn("1耗时：" + (System.currentTimeMillis()  - time));
					out.flush();
					logger.warn("2耗时：" + (System.currentTimeMillis()  - time));
					out.close();
					logger.warn("3耗时：" + (System.currentTimeMillis()  - time));
					if(pool.isPassiveMode()) {
						ftpClient.enterLocalPassiveMode();// Use passive mode to pass firewalls.
					}
					isDo = ftpClient.completePendingCommand();
					logger.warn("4耗时：" + (System.currentTimeMillis()  - time));
				} catch (Exception e) {
					logger.error("续传流关闭处理失败" + remote + e.getMessage());
				}
				//针对linux确认消息优化
				if (isDo || localSize >= lRemoteSize) {
					for (FTPPoolListener lis : lisList) {
						lis.onSuccess(this);
					}
					result = DownloadStatus.Download_From_Break_Success;
				} else {
					for (FTPPoolListener lis : lisList) {
						if(!isFillRetry) 
							lis.onFailed(this);
					}
					result = DownloadStatus.Download_From_Break_Failed;
				}

			} else {
				out = new FileOutputStream(f);
				if(pool.isPassiveMode()) {
					ftpClient.enterLocalPassiveMode();// Use passive mode to pass firewalls.
				}
				InputStream in = ftpClient.retrieveFileStream(new String(remote
						.getBytes("GBK"), "iso-8859-1"));
				byte[] bytes = new byte[4096];
				long step = lRemoteSize / 100;
				long process = 0;
				long localSize = 0L;
				int c;
				while ((c = in.read(bytes)) != -1) {
					logger.warn(remote + "****" + c);
					out.write(bytes, 0, c);
					localSize += c;
					long nowProcess = localSize / step;
					if (nowProcess > process) {
						process = nowProcess;
						if (process % 10 == 0)
							logger.info(remote + "下载进度：" + process + "%");
						// 更新文件下载进度,值存放在process变量中
					}
				}
				logger.info(remote + "下载结束"  + c);
				boolean upNewStatus = false;
				long time = System.currentTimeMillis();
				try {
					
					in.close();
					logger.warn("1耗时：" + (System.currentTimeMillis()  - time));
					out.flush();
					logger.warn("2耗时：" + (System.currentTimeMillis()  - time));
					out.close();
					logger.warn("3耗时：" + (System.currentTimeMillis()  - time));
					upNewStatus = ftpClient.completePendingCommand();
					logger.warn("4耗时：" + (System.currentTimeMillis()  - time));
					if(pool.isPassiveMode()) {
						ftpClient.enterLocalPassiveMode();// Use passive mode to pass firewalls.
					}
					
				} catch (Exception e) {
					logger.error("下载流关闭处理失败" + remote + e.getMessage());
				}
				//针对linux确认消息优化
				if (upNewStatus || localSize >= lRemoteSize) {
					for (FTPPoolListener lis : lisList) {
						lis.onSuccess(this);
					}
					result = DownloadStatus.Download_New_Success;
				} else {
					for (FTPPoolListener lis : lisList) {
						if(!isFillRetry) 
							lis.onFailed(this);
					}
					result = DownloadStatus.Download_New_Failed;
				}
			}
		} catch (Exception e) {
			logger.error("下载文件失败" + remote + e.getMessage());
			for (FTPPoolListener lis : lisList) {
				if(!isFillRetry) 
					lis.onFailed(this);
			}
			result = DownloadStatus.Download_New_Failed;
		} finally {
			if(ftpClient != null) {
				pool.returnResource(ftpClient);
			}
		}  
		return result;
	}

	/**
	 * 上传文件到FTP服务器，支持断点续传
	 * 
	 * @param local
	 *            本地文件名称，绝对路径
	 * @param remote
	 *            远程文件路径，使用/home/directory1/subdirectory/file.ext
	 *            按照Linux上的路径指定方式，支持多级目录嵌套，支持递归创建不存在的目录结构
	 * @param mode
	 *            传输方式：PassiveMode方式，ActiveMode方式
	 * @return 上传结果
	 * @throws IOException
	 */
	protected UploadStatus upload(String local, String remote)
			throws IOException {
		UploadStatus result;
		// 对远程目录的处理
		String remoteFileName = remote;
		FTPClient ftpClient = null;
		try {
			ftpClient = pool.getResource();
			if(pool.isPassiveMode()) {
				ftpClient.enterLocalPassiveMode();// Use passive mode to pass firewalls.
			}
			if (remote.contains("/")) {
				remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
				String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
				if (!directory.equalsIgnoreCase("/")
						&& !ftpClient.changeWorkingDirectory(directory)) {
					// 如果远程目录不存在，则递归创建远程服务器目录
					int start = 0;
					int end = 0;
					if (directory.startsWith("/")) {
						start = 1;
					} else {
						start = 0;
					}
					end = directory.indexOf("/", start);
					while (true) {
						String subDirectory = remote.substring(start, end);
						if (!ftpClient.changeWorkingDirectory(subDirectory)) {
							if (ftpClient.makeDirectory(subDirectory)) {
								ftpClient.changeWorkingDirectory(subDirectory);
							} else {
								logger.error("创建目录失败");
								return UploadStatus.Create_Directory_Fail;
							}
						}

						start = end + 1;
						end = directory.indexOf("/", start);

						// 检查所有目录是否创建完毕
						if (end <= start) {
							break;
						}
					}
				}
			}

			// 检查远程是否存在文件
			FTPFile[] files = ftpClient.listFiles(remoteFileName);
			if (files.length == 1) {
				long remoteSize = files[0].getSize();
				File f = new File(local);
				long localSize = f.length();
				if (remoteSize == localSize) {
					logger.error("文件已存在！请重新命名");
					return UploadStatus.File_Exits;
				} else if (remoteSize > localSize) {
					return UploadStatus.Remote_Bigger_Local;
				}

				// 尝试移动文件内读取指针,实现断点续传
				InputStream is = new FileInputStream(f);
				if (is.skip(remoteSize) == remoteSize) {
					ftpClient.setRestartOffset(remoteSize);
					if (ftpClient.storeFile(new String(remote.getBytes("GBK"),
							"iso-8859-1"), is)) {
						logger.info("断点续传成功！");
						is.close();
						return UploadStatus.Upload_From_Break_Success;
					}
				}
				// 如果断点续传没有成功，则删除服务器上文件，重新上传
				if (!ftpClient.deleteFile(remoteFileName)) {
					logger.info("删除文件成功!");
					return UploadStatus.Delete_Remote_Faild;
				}
				is = new FileInputStream(f);
				if (ftpClient.storeFile(new String(remote.getBytes("GBK"),
						"iso-8859-1"), is)) {
					logger.info("文件重新上传成功！");
					result = UploadStatus.Upload_New_File_Success;
				} else {
					logger.error("文件重新上传失败！");
					result = UploadStatus.Upload_New_File_Failed;
				}
				is.close();
			} else {
				InputStream is = new FileInputStream(local);
				if (ftpClient.storeFile(new String(remoteFileName.getBytes("GBK"),
						"iso-8859-1"), is)) {
					logger.info("文件上传成功！");
					result = UploadStatus.Upload_New_File_Success;
				} else {
					logger.error("文件上传失败！");
					result = UploadStatus.Upload_New_File_Failed;
				}
				is.close();
			}
		} catch (Exception e) {
			logger.error("文件上传失败" + remote + e.getMessage());
			result = UploadStatus.Upload_New_File_Failed;
		} finally {
			if(ftpClient != null) {
				pool.returnResource(ftpClient);
			}
		}  
		return result;
	}

	public enum UploadStatus {
		Create_Directory_Fail, // 远程服务器相应目录创建失败
		Create_Directory_Success, // 远程服务器闯将目录成功
		Upload_New_File_Success, // 上传新文件成功
		Upload_New_File_Failed, // 上传新文件失败
		File_Exits, // 文件已经存在
		Remote_Bigger_Local, // 远程文件大于本地文件
		Upload_From_Break_Success, // 断点续传成功
		Upload_From_Break_Failed, // 断点续传失败
		Delete_Remote_Faild; // 删除远程文件失败
	}

	public enum DownloadStatus {
		Remote_File_Noexist, // 远程文件不存在
		Download_New_Success, // 下载文件成功
		Download_New_Failed, // 下载文件失败
		Local_Bigger_Remote, // 本地文件大于远程文件
		Download_From_Break_Success, // 断点续传成功
		Download_From_Break_Failed; // 断点续传失败
	}
	
	
	/**
	 * 获取本地路径
	 * @return
	 */
	public String getLocal() {
		return local;
	}
	public String getTime() {
		return time;
	}
	public String getFileName() {
		return fileName;
	}
	public String getRemote() {
		return remote;
	}
}
